import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Button } from "antd";

const InformTwo = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { state } = location;
  const [animationStage, setAnimationStage] = useState(0);
  const [imageError, setImageError] = useState(false);

  useEffect(() => {
    const baguaTimer = setTimeout(() => setAnimationStage(1), 3000);
    const progressTimer = setTimeout(() => setAnimationStage(2), 5000);
    return () => {
      clearTimeout(baguaTimer);
      clearTimeout(progressTimer);
    };
  }, []);

  const handleImageError = () => setImageError(true);

  const handleViewResult = () => {
    navigate("/maiFortune", { state });
  };

  const calculateWuXing = (birthYear) => {
    const heavenlyStems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
    const earthlyBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
    console.log(earthlyBranches);
    
    const wuXingMap = { 甲: "木", 乙: "木", 丙: "火", 丁: "火", 戊: "土", 己: "土", 庚: "金", 辛: "金", 壬: "水", 癸: "水" };
    const stemIndex = (birthYear - 4) % 10;
    const stem = heavenlyStems[stemIndex];
    const birthdayWuXing = wuXingMap[stem];
    const year2025WuXing = "木";
    console.log(year2025WuXing);
    
    let daXianWuXing = "", fortune = "", taboo = "";
    if (birthdayWuXing === "木") {
      daXianWuXing = "木强（木得生）";
      fortune = "2025年运势顺畅，适宜抓住机会，但需注意情绪管理。";
      taboo = "忌讳过于急躁，宜多与水、火属性的人合作。";
    } else if (birthdayWuXing === "火") {
      daXianWuXing = "火得生（木生火）";
      fortune = "2025年运势旺盛，但需注意过度消耗精力。";
      taboo = "忌讳过度劳累，宜多接触水属性事物。";
    } else if (birthdayWuXing === "土") {
      daXianWuXing = "土受克（木克土）";
      fortune = "2025年运势有阻力，宜低调行事。";
      taboo = "忌讳冒险，宜增强土气（如穿黄色）。";
    } else if (birthdayWuXing === "金") {
      daXianWuXing = "金受生（土生金）";
      fortune = "2025年运势平稳，有突破机会。";
      taboo = "忌讳锋芒毕露，宜接触土属性事物。";
    } else if (birthdayWuXing === "水") {
      daXianWuXing = "水得生（金生水）";
      fortune = "2025年运势平稳，适宜提升自己。";
      taboo = "忌讳保守，宜接触金属性事物。";
    }
    return { birthdayWuXing, daXianWuXing, fortune, taboo };
  };

  const wuXingInfo = state?.birthYear ? calculateWuXing(parseInt(state.birthYear)) : {
    birthdayWuXing: "未知",
    daXianWuXing: "未知",
    fortune: "请提供完整信息以获取运势。",
    taboo: "请提供完整信息以获取建议。",
  };

  return (
    <div
      style={{
        backgroundColor: "#f1c588",
        width: "600px",
        margin: "0 auto",
        paddingBottom: "60px",
        position: "relative",
        minHeight: "100vh",
        overflow: "auto",
      }}
    >
      {animationStage === 0 && (
        <div
          style={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            zIndex: 10,
          }}
        >
          {imageError ? (
            <div
              style={{
                width: "150px",
                height: "150px",
                backgroundColor: "#ccc",
                borderRadius: "50%",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                color: "white",
                fontSize: "16px",
                textAlign: "center",
                animation: "spin 2s linear infinite",
              }}
            >
              八卦图片加载失败
            </div>
          ) : (
            <img
              src="https://th.bing.com/th/id/OIP.b2JVrY4fQI6Gjr8STL1ycgHaHa?rs=1&pid=ImgDetMain"
              alt="八卦转轮"
              style={{
                width: "150px",
                height: "150px",
                animation: "spin 2s linear infinite",
                borderRadius: "50%",
                backgroundColor: "transparent",
              }}
              onError={handleImageError}
            />
          )}
          <p style={{ marginTop: "20px", fontSize: "18px", color: "#333", textAlign: "center" }}>
            正在为您解析八字运程...
          </p>
        </div>
      )}

      {animationStage === 1 && (
        <div
          style={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            width: "80%",
            textAlign: "center",
            zIndex: 10,
          }}
        >
          <p style={{ fontSize: "20px", color: "#b22222", marginBottom: "10px" }}>
            正在生成你的2025年运程
          </p>
          <div
            style={{
              width: "100%",
              height: "20px",
              backgroundColor: "#fff5e1",
              border: "2px solid #b22222",
              borderRadius: "10px",
              overflow: "hidden",
            }}
          >
            <div
              style={{
                width: "0%",
                height: "100%",
                backgroundColor: "#ffaa00",
                animation: "progress 2s ease-in-out forwards",
              }}
            />
          </div>
          <p style={{ marginTop: "10px", fontSize: "14px", color: "#666" }}>
            正在生成你的2025年运程报告
          </p>
        </div>
      )}

      {animationStage === 2 && (
        <div>
          <img
            style={{
              width: "100%",
              height: "auto",
              position: "absolute",
              top: 0,
              left: 0,
              zIndex: 1,
            }}
            src="https://zx.tengzhihh.com/bdshengchenyunshi/static/bg.f57a80ca.jpg"
            alt="背景图"
          />
          <div style={{ position: "relative", zIndex: 2, padding: "20px" }}>
            <div
              style={{
                textAlign: "center",
                marginBottom: "20px",
                backgroundColor: "#fff5e1",
                padding: "15px",
                border: "4px solid #b22222",
                borderRadius: "10px",
                boxShadow: "0 4px 12px rgba(0, 0, 0, 0.2)",
              }}
            >
              <h2 style={{ color: "#b22222", fontSize: "24px", marginBottom: "10px" }}>
                正在揭秘你的2025流年运程
              </h2>
              <p style={{ color: "#333", fontSize: "18px" }}>
                你的生日五行为：{wuXingInfo.birthdayWuXing}
              </p>
              <p style={{ color: "#333", fontSize: "18px" }}>
                大限五行：{wuXingInfo.daXianWuXing}
              </p>
              <p style={{ color: "#333", fontSize: "16px", marginTop: "10px" }}>
                2025年，{state?.name}，{wuXingInfo.fortune}
              </p>
            </div>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", marginBottom: "20px" }}>
              <Button
                type="primary"
                onClick={handleViewResult}
                style={{
                  padding: "12px 40px",
                  backgroundColor: "#ffaa00",
                  borderColor: "#b22222",
                  borderRadius: "30px",
                  fontSize: "18px",
                  fontWeight: "bold",
                  height: "auto",
                  boxShadow: "0 4px 12px rgba(0, 0, 0, 0.3)",
                  transition: "transform 0.1s ease-in-out",
                }}
                onMouseDown={(e) => (e.target.style.transform = "scale(0.95)")}
                onMouseUp={(e) => (e.target.style.transform = "scale(1)")}
              >
                查看详细运势报告
              </Button>
            </div>
            <div
              style={{
                textAlign: "center",
                backgroundColor: "#fff5e1",
                padding: "15px",
                border: "4px solid #b22222",
                borderRadius: "10px",
                boxShadow: "0 4px 12px rgba(0, 0, 0, 0.2)",
              }}
            >
              <p style={{ color: "#333", fontSize: "16px" }}>
                命盘显示，2025年你的运势特点：{wuXingInfo.fortune}
              </p>
              <p style={{ color: "#b22222", fontSize: "16px", fontWeight: "bold" }}>
                禁忌建议：{wuXingInfo.taboo}
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const styles = `
  @keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }
  @keyframes progress {
    from { width: 0%; }
    to { width: 100%; }
  }
`;

const styleSheet = document.createElement("style");
styleSheet.type = "text/css";
styleSheet.innerText = styles;
document.head.appendChild(styleSheet);

export default InformTwo;